function urlToBase64(src) {
  return new Promise((resolve, reject) => {
    // 获取图片的type
    let type = src.slice(src.lastIndexOf('.') + 1, src.length);
    var canvas = document.createElement('canvas');
    var img = document.createElement('img');
    // 设置可以跨域
    img.setAttribute('crossOrigin', 'anonymous');
    img.src = src;
    img.onload = function () {
      canvas.width = img.width;
      canvas.height = img.height;
      var context = canvas.getContext('2d');
      context.drawImage(img, 0, 0, img.width, img.height);
      let base64 = canvas.toDataURL('image/' + type);
      resolve(base64);
    };
  });
}
//  base64 => file
function dataURLtoFile(dataurl, filename, src) {
  return new Promise((resolve, reject) => {
    var arr = dataurl.split(','),
      mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]),
      n = bstr.length,
      u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    let file = {};
    file.originFileObj = new File([u8arr], filename, { type: mime });
    file.name = filename;
    resolve(file);
  });
}

export default {
  urlToBase64,
  dataURLtoFile,
};
